﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;

namespace ServerASISTSYS
{
    public class ServerFunctions
    {
        public static List<TcpClient> tcpClientList = new List<TcpClient>();
        public string CNP { get; set; }

        public void SendAlertMessage(string CNP, int IdSenzor, string Msg)
        {
            foreach (TcpClient client in tcpClientList)
            {
                try
                {
                    ASCIIEncoding asen = new ASCIIEncoding();

                    Stream stm = client.GetStream();
                    byte[] buff = new byte[4096], tmp;
                    int msgLen, cnpLen;

                    // lungime
                    msgLen = asen.GetBytes(Msg).Length;
                    cnpLen = asen.GetBytes(CNP).Length;

                    tmp = BitConverter.GetBytes(msgLen + cnpLen + 4);
                    for (int i = 0; i < 4; i++)
                        buff[i] = tmp[i];

                    // CNP
                    tmp = asen.GetBytes(CNP);
                    for (int i = 0; i < cnpLen; i++)
                        buff[4 + i] = tmp[i];

                    // IdSenzor
                    tmp = BitConverter.GetBytes(IdSenzor);
                    for (int i = 0; i < 4; i++)
                        buff[17 + i] = tmp[i];

                    // Msg
                    tmp = asen.GetBytes(Msg);
                    for (int i = 0; i < msgLen; i++)
                        buff[21 + i] = tmp[i];

                    // transmitere
                    stm.Write(buff, 0, 4 + cnpLen + 4 + msgLen);

                    Console.WriteLine("Alerta: " + Msg);
                }
                catch//(Exception x)
                {
                    // daca s-a produs o exceptie inchidem clientul si il stergem in lista
                    client.Close();
                    tcpClientList.Remove(client);

                    Console.WriteLine("EXCEPTION in ServerFunctions: Client ?? has been closed.");
                }
            } /* foreach */
        } /* SendAlertMessage */

        public void AddGUIClient(TcpClient gui)
        {
            tcpClientList.Add(gui);
        }
    }
}
